import React, { useState, useEffect } from 'react';
// 使用正确的导入路径
import { Card, CardContent, Typography, Button, Box, TextField, Divider, Paper } from '@mui/material';
// 确保安装了@mui/material包: npm install @mui/material
// Import missing components
import { useToast, ToastProps } from '@/components/ui/use-toast';
import { PieChart, Pie, Cell, ResponsiveContainer, BarChart, Bar, XAxis, YAxis, Tooltip, Legend } from 'recharts';
import { ChevronDown, ChevronUp, CheckCircle, AlertCircle, Clock, Calendar, Search, Menu, X } from 'lucide-react';
import { supabase } from '@/lib/supabase/client';
import { motion } from 'framer-motion';

// Define types
interface SupportExercise {
  id: string;
  title: string;
  description: string;
  category: 'breathing' | 'meditation' | 'mindfulness' | 'grounding' | 'cognitive';
  duration: number;
  difficulty: 'beginner' | 'intermediate' | 'advanced';
  completed: boolean;
  completion_rate: number;
  last_completed: string | null;
}

interface CategoryStats {
  name: string;
  value: number;
}

interface CompletionData {
  name: string;
  completed: number;
  total: number;
}

// Mock data
const mockExercises: SupportExercise[] = [
  {
    id: '1',
    title: 'Deep Breathing',
    description: 'A simple breathing exercise to calm your mind and reduce stress.',
    category: 'breathing',
    duration: 5,
    difficulty: 'beginner',
    completed: true,
    completion_rate: 85,
    last_completed: '2023-11-15T09:30:00Z'
  },
  {
    id: '2',
    title: 'Body Scan Meditation',
    description: 'A mindfulness meditation focusing on physical sensations throughout your body.',
    category: 'meditation',
    duration: 10,
    difficulty: 'beginner',
    completed: false,
    completion_rate: 0,
    last_completed: null
  },
  {
    id: '3',
    title: '5-4-3-2-1 Grounding',
    description: 'A technique to ground yourself in the present moment using your senses.',
    category: 'grounding',
    duration: 3,
    difficulty: 'beginner',
    completed: true,
    completion_rate: 100,
    last_completed: '2023-11-14T14:15:00Z'
  },
  {
    id: '4',
    title: 'Thought Challenging',
    description: 'Identify and challenge negative thought patterns.',
    category: 'cognitive',
    duration: 15,
    difficulty: 'intermediate',
    completed: false,
    completion_rate: 0,
    last_completed: null
  },
  {
    id: '5',
    title: 'Loving-Kindness Meditation',
    description: 'Cultivate feelings of compassion and kindness towards yourself and others.',
    category: 'meditation',
    duration: 12,
    difficulty: 'intermediate',
    completed: true,
    completion_rate: 70,
    last_completed: '2023-11-12T20:45:00Z'
  }
];

// Category stats data
const categoryStats: CategoryStats[] = [
  { name: 'Breathing', value: 1 },
  { name: 'Meditation', value: 2 },
  { name: 'Grounding', value: 1 },
  { name: 'Cognitive', value: 1 },
  { name: 'Mindfulness', value: 0 }
];

// Completion data
const completionData: CompletionData[] = [
  { name: 'Today', completed: 2, total: 5 },
  { name: 'This Week', completed: 3, total: 5 },
  { name: 'This Month', completed: 3, total: 5 }
];

// Colors
const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042', '#8884d8'];

export default function QuickSupport() {
  const [exercises, setExercises] = useState<SupportExercise[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
  const [expandedExercise, setExpandedExercise] = useState<string | null>(null);
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  // 使用正确的类型
const toast = useToast();

  useEffect(() => {
    // Fetch exercises from Supabase
    const fetchExercises = async () => {
      try {
        setLoading(true);
        // In a real implementation, you would fetch from Supabase
        // const { data, error } = await supabase
        //   .from('support_exercises')
        //   .select('*')
        //   .eq('user_id', userId);

        // For now, use mock data
        setTimeout(() => {
          setExercises(mockExercises);
          setLoading(false);
        }, 800);
      } catch (error) {
        console.error('Error fetching exercises:', error);
        toast({ status: 'error', title: 'Failed to load exercises', description: 'Please try again later.' });
        setLoading(false);
      }
    };

    fetchExercises();
  }, [toast]);

  // Filter exercises based on search term and category
  const filteredExercises = exercises.filter(exercise => {
    const matchesSearch = exercise.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         exercise.description.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesCategory = !selectedCategory || exercise.category === selectedCategory;
    return matchesSearch && matchesCategory;
  });

  // Toggle exercise expansion
  const toggleExercise = (id: string): void => {
    setExpandedExercise(expandedExercise === id ? null : id);
  };

  // Mark exercise as completed
  const markAsCompleted = async (id: string): Promise<void> => {
    try {
      // In a real implementation, you would update Supabase
      // const { data, error } = await supabase
      //   .from('support_exercises')
      //   .update({ completed: true, last_completed: new Date().toISOString() })
      //   .eq('id', id)
      //   .select();

      // For now, update locally
      setExercises(exercises.map(exercise =>
        exercise.id === id
          ? { ...exercise, completed: true, last_completed: new Date().toISOString(), completion_rate: 100 }
          : exercise
      ));
      toast({ status: 'success', title: 'Exercise completed', description: 'Great job!' });
    } catch (error) {
      console.error('Error updating exercise:', error);
      toast({ status: 'error', title: 'Failed to update exercise', description: 'Please try again later.' });
    }
  };

  // Handle category change
  const handleCategoryChange = (category: string): void => {
    setSelectedCategory(selectedCategory === category ? null : category);
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-screen bg-gray-50">
        <motion.div
          initial={{ opacity: 0, scale: 0.8 }}
          animate={{ opacity: 1, scale: 1 }}
          transition={{ duration: 0.5 }}
          className="flex flex-col items-center"
        >
          <div className="w-16 h-16 border-4 border-blue-500 border-t-transparent rounded-full animate-spin"></div>
          <Typography variant="h6" className="mt-4 text-blue-600">Loading quick support exercises...</Typography>
        </motion.div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <header className="bg-white shadow-md">
        <div className="container mx-auto px-4 py-4 flex justify-between items-center">
          <Typography variant="h5" className="font-bold text-blue-600">Quick Support</Typography>
          <div className="hidden md:flex items-center space-x-4">
            <TextField
              variant="outlined"
              placeholder="Search exercises..."
              size="small"
              value={searchTerm}
              onChange={(e: React.ChangeEvent<HTMLInputElement>) => setSearchTerm(e.target.value)}
              InputProps={{
                startAdornment: <Search size={18} className="mr-2 text-gray-400" />
              }}
            />
          </div>
          <Button
            variant="contained"
            color="primary"
            className="md:hidden"
            onClick={(e: React.MouseEvent<HTMLButtonElement>) => setMobileMenuOpen(!mobileMenuOpen)}
          >
            {mobileMenuOpen ? <X /> : <Menu />}
          </Button>
        </div>
      </header>

      {/* Mobile menu */}
      {mobileMenuOpen && (
        <motion.div
          initial={{ opacity: 0, height: 0 }}
          animate={{ opacity: 1, height: 'auto' }}
          exit={{ opacity: 0, height: 0 }}
          className="md:hidden bg-white shadow-lg p-4"
        >
          <TextField
            variant="outlined"
            placeholder="Search exercises..."
            fullWidth
            size="small"
            value={searchTerm}
            onChange={(e: React.ChangeEvent<HTMLInputElement>) => setSearchTerm(e.target.value)}
            InputProps={{
              startAdornment: <Search size={18} className="mr-2 text-gray-400" />
            }}
            className="mb-4"
          />
        </motion.div>
      )}

      <main className="container mx-auto px-4 py-8">
        <div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
          {/* Sidebar */}
          <div className="lg:col-span-1 space-y-6">
            {/* Stats Card */}
            <Card className="shadow-md hover:shadow-lg transition-shadow duration-300">
              <CardContent>
                <Typography variant="h6" className="font-bold mb-4 text-gray-700">Exercise Statistics</Typography>
                <div className="h-64">
                  <ResponsiveContainer width="100%" height="100%">
                    <PieChart>
                      <Pie
                        data={categoryStats}
                        cx="50%"
                        cy="50%"
                        labelLine={false}
                        outerRadius={80}
                        fill="#8884d8"
                        dataKey="value"
                        label={({ name, percent }) => `${name}: ${((percent || 0) * 100).toFixed(0)}%`}
                      >
                        {categoryStats.map((entry, index) => (
                          <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                        ))}
                      </Pie>
                      <Tooltip />
                      <Legend layout="vertical" align="right" verticalAlign="middle" />
                    </PieChart>
                  </ResponsiveContainer>
                </div>
              </CardContent>
            </Card>

          </div>

          {/* Main content */}
          <div className="lg:col-span-3 space-y-6">
            <Typography variant="h4" className="font-bold text-gray-800">Available Exercises</Typography>

            {/* Category filters */}
            <div className="flex flex-wrap gap-2 mb-6">
              <Button
                variant={!selectedCategory ? "contained" : "outlined"}
                color="primary"
                onClick={(e: React.MouseEvent<HTMLButtonElement>) => handleCategoryChange('')}
              >
                All
              </Button>
              <Button
                variant={selectedCategory === 'breathing' ? "contained" : "outlined"}
                color="primary"
                onClick={(e: React.MouseEvent<HTMLButtonElement>) => handleCategoryChange('breathing')}
              >
                Breathing
              </Button>
              <Button
                variant={selectedCategory === 'meditation' ? "contained" : "outlined"}
                color="primary"
                onClick={(e: React.MouseEvent<HTMLButtonElement>) => handleCategoryChange('meditation')}
              >
                Meditation
              </Button>
              <Button
                variant={selectedCategory === 'mindfulness' ? "contained" : "outlined"}
                color="primary"
                onClick={(e: React.MouseEvent<HTMLButtonElement>) => handleCategoryChange('mindfulness')}
              >
                Mindfulness
              </Button>
              <Button
                variant={selectedCategory === 'grounding' ? "contained" : "outlined"}
                color="primary"
                onClick={(e: React.MouseEvent<HTMLButtonElement>) => handleCategoryChange('grounding')}
              >
                Grounding
              </Button>
              <Button
                variant={selectedCategory === 'cognitive' ? "contained" : "outlined"}
                color="primary"
                onClick={(e: React.MouseEvent<HTMLButtonElement>) => handleCategoryChange('cognitive')}
              >
                Cognitive
              </Button>
            </div>

            {/* Exercises list */}
            {filteredExercises.length > 0 ? (
              filteredExercises.map((exercise) => (
                <motion.div
                  key={exercise.id}
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.5 }}
                  className="bg-white rounded-lg shadow-md overflow-hidden"
                >
                  <div
                    className="p-4 flex justify-between items-center cursor-pointer"
                    onClick={(e: React.MouseEvent<HTMLDivElement>) => toggleExercise(exercise.id)}
                  >
                    <div className="flex items-center space-x-3">
                      <div className={`w-10 h-10 rounded-full flex items-center justify-center ${exercise.completed ? 'bg-green-100 text-green-600' : 'bg-gray-100 text-gray-400'}`}>
                        {exercise.completed ? <CheckCircle size={20} /> : <AlertCircle size={20} />}
                      </div>
                      <div>
                        <Typography variant="h6" className="font-bold text-gray-800">{exercise.title}</Typography>
                        <div className="flex items-center text-sm text-gray-500 mt-1">
                          <Clock size={14} className="mr-1" />
                          <span>{exercise.duration} min</span>
                          <span className="mx-2">•</span>
                          <span>{exercise.difficulty.charAt(0).toUpperCase() + exercise.difficulty.slice(1)}</span>
                        </div>
                      </div>
                    </div>
                    {expandedExercise === exercise.id ? <ChevronUp size={20} /> : <ChevronDown size={20} />}
                  </div>

                  {expandedExercise === exercise.id && (
                    <motion.div
                      initial={{ opacity: 0, height: 0 }}
                      animate={{ opacity: 1, height: 'auto' }}
                      exit={{ opacity: 0, height: 0 }}
                      className="px-4 pb-4"
                    >
                      <Divider className="my-3" />
                      <Typography variant="body1" className="text-gray-600 mb-3">{exercise.description}</Typography>
                      <div className="flex justify-between items-center">
                        <div className="flex items-center space-x-4">
                          <div className="flex items-center text-sm text-gray-500">
                            <Calendar size={14} className="mr-1" />
                            <span>
                              {exercise.last_completed
                                ? new Date(exercise.last_completed).toLocaleDateString()
                                : 'Never completed'}
                            </span>
                          </div>
                        </div>
                        {!exercise.completed && (
                          <Button
                            variant="contained"
                            color="primary"
                            onClick={(e: React.MouseEvent<HTMLButtonElement>) => markAsCompleted(exercise.id)}
                          >
                            Mark as Completed
                          </Button>
                        )}
                      </div>
                    </motion.div>
                  )}
                </motion.div>
              ))
            ) : (
              <Paper className="p-6 text-center">
                <Typography variant="h6" className="text-gray-500">No exercises found</Typography>
                <Typography variant="body2" className="text-gray-400 mt-2">Try adjusting your search or filters</Typography>
              </Paper>
            )}
          </div>
        </div>
      </main>
    </div>
  );
}